package com.standardoperationapp.materialinventory.activity;



import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.bumptech.glide.Glide;
import com.cl.picture_selector.ImagePicker;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.standardoperationapp.R;
import com.standardoperationapp.bean.MaterQrCodeBean;
import com.standardoperationapp.databinding.ActivityListItemBinding;
import com.standardoperationapp.global.DateUtils;
import com.standardoperationapp.global.GlobalVaries;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.global.ListViewItem;
import com.standardoperationapp.net.MaterialApi;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;
import com.standardoperationapp.utils.FileUtils;
import com.standardoperationapp.utils.GlideLoader;
import com.standardoperationapp.utils.ToastUtil;
import com.yayandroid.locationmanager.LocationManager;
import com.yayandroid.locationmanager.configuration.Configurations;
import com.yayandroid.locationmanager.listener.LocationListener;
import com.yayandroid.locationmanager.providers.locationprovider.DefaultLocationProvider;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ListItemActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 100;
    public static final int PERMISSION_REQUEST_CODE = 110;
    private ActivityListItemBinding binding;
    private ActivityResultLauncher<PickVisualMediaRequest> launcher;

    private static final int DECODE_OUTPUT_MODE_INTENT = 0;
    private static final int DECODE_OUTPUT_MODE_FOCUS = 1;
    private static final int MSG_SHOW_SCAN_RESULT = 1;
    private ScanManager mScanManager = null;

    private static final int[] SCAN_KEYCODE = {520, 521, 522, 523};


    private ListViewItem data;
    private String imageUrl;

    /**
     * 当前物资id
     */
    int materId;
    String addressName = "";

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogD("onReceive--------------------------- , action:" + action);
            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodeLen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            String barcodeStr = intent.getStringExtra(ScanManager.BARCODE_STRING_TAG);
            Message msg = mHandler.obtainMessage(MSG_SHOW_SCAN_RESULT);
            msg.obj = barcodeStr;
            mHandler.sendMessage(msg);
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SHOW_SCAN_RESULT:
                    String scanResult = (String) msg.obj;
                    Log.d(TAG, "扫描结果: " +scanResult);
                    try {
                        MaterQrCodeBean bean = GsonUtils.fromJson(scanResult, MaterQrCodeBean.class);
                        if (bean.getId() == null) {
                            ToastUtil.showToast("物资二维码异常，缺少id信息");
                            return;
                        }
                        // {"addressName":"A-2-1103-2-2-1103-2","id":22,"materCode":"QZ0001","materName":"钳子"}
                        if (bean.getId() == materId) {
                            int count = 0;
                            try {
                                count = Integer.parseInt(binding.etCount2.getText().toString());
                            } catch (Exception e) {

                            }
                            binding.etCount2.setText((count + 1) +"");
                        } else {
                            ToastUtil.showToast("请扫码对应的物资二维码");
                        }
                    } catch (Exception e) {
                        ToastUtil.showToast("物资二维码解析错误");
                    }

                    break;
            }
        }
    };
    private LocationManager awesomeLocationManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_list_item);

        String title=getIntent().getStringExtra("title");
        data= (ListViewItem) getIntent().getSerializableExtra("bean");
        materId = data.getId();

        binding.setData(data);


        if (GlobalVaries.uiType == GlobalVaries.XIANCHANGWUZI) {
            Glide.with(this).load(data.getImgUrl()).into(binding.ivImage);
        }

        initView(title);

        initLocation();
        launcher = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                Log.d("PhotoPicker", "Selected URI: " + uri);
                String path = FileUtils.getRealPathFromUri(this, uri);
                Log.d("PhotoPicker", "Selected path: " + path);
                uploadPhoto(path);
            } else {
                Log.d("PhotoPicker", "No media selected");
            }
        });
    }

    private void initScanManager() {
        try {
            mScanManager = new ScanManager();
            boolean powerOn = mScanManager.getScannerState();
//                if (!powerOn) {
//                    powerOn = mScanManager.openScanner();
//                    if (!powerOn) {
//                        AlertDialog.Builder builder = new AlertDialog.Builder(ListItemActivity.this);
//                        builder.setMessage("Scanner cannot be turned on!");
//                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//                        AlertDialog mAlertDialog = builder.create();
//                        mAlertDialog.show();
//                    }
//                }
            mScanManager.switchOutputMode(DECODE_OUTPUT_MODE_INTENT);
            if (mScanManager.getTriggerLockState()) {
                // 如果禁用扫描按钮，需要启用
                mScanManager.unlockTrigger();
            }
//        mScanManager.startDecode();
            mScanManager.enableAllSymbologies(true);
        } catch (Exception e) {
            Log.d(TAG, "initScanManager: 扫描器开启失败" );
            mScanManager = null;
        }


    }

    @Override
    protected void onPause() {
        super.onPause();
        registerReceiver(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScanManager();
        registerReceiver(true);
    }


    private void registerReceiver(boolean register) {
        if (register && mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME,
                    PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
            String[] value_buf = mScanManager.getParameterString(idbuf);
            if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
                filter.addAction(value_buf[0]);
            } else {
                filter.addAction(ScanManager.ACTION_DECODE);
            }
            registerReceiver(mReceiver, filter);
        } else if (mScanManager != null) {
            mScanManager.stopDecode();
            unregisterReceiver(mReceiver);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        LogD("onKeyUp, keyCode:" + keyCode);
        if (keyCode >= SCAN_KEYCODE[0] && keyCode <= SCAN_KEYCODE[SCAN_KEYCODE.length - 1]) {
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogD("onKeyDown, keyCode:" + keyCode);
        if (keyCode >= SCAN_KEYCODE[0] && keyCode <= SCAN_KEYCODE[SCAN_KEYCODE.length - 1]) {
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initView(String title) {
        binding.tvTitle.setText(title);
        if (GlobalVaries.uiType == GlobalVaries.KUCUNBUCHONG) {
            binding.tvCount1Label.setText("补充数量");
        } else if (GlobalVaries.uiType == GlobalVaries.LINGYONG) {
            binding.tvCount1Label.setText("领用数量");
        } else if (GlobalVaries.uiType == GlobalVaries.DIAOBO) {
            binding.tvCount1Label.setText("调拨数量");
        } else if (GlobalVaries.uiType == GlobalVaries.XIAOHAO) {
            binding.tvCount1Label.setText("消耗数量");
        } else if (GlobalVaries.uiType == GlobalVaries.baoFei) {
            binding.tvCount1Label.setText("报废数量");
        } else if (GlobalVaries.uiType == GlobalVaries.PANDIAN) {
            binding.tvCount1Label.setText("库存数量");
            binding.tvCount2Label.setText("盘点数量");
        } else if (GlobalVaries.uiType == GlobalVaries.XIANCHANGWUZI) {
            binding.tvCount1Label.setText("数量");
            binding.tvCount2Label.setText("盘点数量");
        }
        if (GlobalVaries.uiType == GlobalVaries.LINGYONG && GlobalVaries.inOutType == GlobalVaries.inBound) {
            binding.llTime.setVisibility(View.VISIBLE);
            binding.tvTime.setText(DateUtils.getStringDate());
        } else {
            binding.llTime.setVisibility(View.GONE);
        }
        if (GlobalVaries.uiType == GlobalVaries.XIANCHANGWUZI) {
            if (data.getPosition().contains("-")) {
                String[] split = data.getPosition().split("-");
                binding.tvAddress1.setText(split[0]);
                binding.tvAddress2.setText(split[1]);
            } else {
                binding.tvAddress1.setText(data.getPosition());
            }

        }

        binding.cancelBtn.setOnClickListener(view -> finish());
        binding.confirmBtn.setOnClickListener(view -> {
            // 扫码数量
            String count = binding.etCount2.getText().toString();
            data.setScanno(Double.parseDouble(count));
            if (GlobalVaries.uiType == GlobalVaries.LINGYONG && GlobalVaries.inOutType == GlobalVaries.inBound) {
                data.setReturnTime(binding.tvTime.getText().toString());
            }
            String lat = binding.tvLat.getText().toString();
            String lon = binding.tvLon.getText().toString();
            data.setLat(Double.parseDouble(lat.isEmpty() ? "0" : lat));
            data.setLon(Double.parseDouble(lon.isEmpty() ? "0" : lon));
            data.setImgUrl(imageUrl);
            Intent intent = new Intent();
            intent.putExtra("data",data);
            setResult(RESULT_OK,intent);
            finish();
        });
        binding.btnTakePhoto.setOnClickListener(view -> {
            // 打开相机
            requestPermission();
        });
        binding.btnGetLocation.setOnClickListener(view -> awesomeLocationManager.get());
    }


    /**
     * 申请动态权限
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
        } else {
            takePhoto();
        }
    }

    // 选择照片
    private void takePhoto() {
        if (Build.VERSION.SDK_INT >= 33) {
            launcher.launch(new PickVisualMediaRequest.Builder()
                    .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                    .build());
        } else {
            //单选
//            ImageSelector.builder().useCamera(true) // 设置是否使用拍照
//                    .setSingle(true)  //设置是否单选
//                    .canPreview(true) //是否可以预览图片，默认为true
//                    .start(this, REQUEST_CODE); // 打开相册
            ImagePicker.getInstance()
                    .setTitle("选择照片")//设置标题
                    .showCamera(true)//设置是否显示拍照按钮
                    .showImage(true)//设置是否展示图片
                    .showVideo(false)//设置是否展示视频
                    .showLoading(true, "")   //是否显示首次加载框--加载框标题
                    .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true)//设置图片视频不能同时选择
                    .setImageLoader(new GlideLoader())//设置自定义图片加载器
                    .start(this, REQUEST_CODE);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            //获取选择器返回的数据
            List<String> images = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            uploadPhoto(images.get(0));

        }
    }

    private void uploadPhoto(String path){
        Glide.with(this).load(path).into(binding.ivImage);
        File mFile = new File(path);
        // 上传文件参数
        RequestBody body = RequestBody.create(MediaType.parse("image/jpg"), mFile);
        MultipartBody.Part file = MultipartBody.Part.createFormData("file", mFile.getName(), body);

        MaterialApi.uploadFile(file, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                Log.d(TAG, "onSuccess: 上传文件成功： " + result.toString());
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    JSONObject data = jsonObject.getJSONObject("data");
                    imageUrl = data.getString("url");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast("照片上传失败：" + errorMsg);
            }
        }));
    }


    private static final String TAG = "ListItemActivity";
    private void LogD(String msg) {
        android.util.Log.d(TAG, msg);
    }

    private void LogI(String msg) {
        android.util.Log.i(TAG, msg);
    }

    private void initLocation() {

        awesomeLocationManager = new LocationManager.Builder(getApplicationContext())
                .activity(this) // Only required to ask permission and/or GoogleApi - SettingsApi
                .configuration(Configurations.defaultConfiguration("tishi", "sssssssssssss"))
                .locationProvider(new DefaultLocationProvider())
                .notify(new LocationListener() {
                    @Override
                    public void onProcessTypeChanged(int processType) {
                        Log.d(TAG, "onProcessTypeChanged: " + processType);
                    }

                    @Override
                    public void onLocationChanged(Location location) {
                        double latitude = location.getLatitude();
                        double longitude = location.getLongitude();
                        binding.tvLat.setText(latitude + "");
                        binding.tvLon.setText(longitude + "");
                        Log.d(TAG, "onLocationChanged: " + location);
                    }

                    @Override
                    public void onLocationFailed(int type) {
                        Log.d(TAG, "onLocationFailed: " + type);

                    }

                    @Override
                    public void onPermissionGranted(boolean alreadyHadPermission) {
                        Log.d(TAG, "onPermissionGranted: ");
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                        Log.d(TAG, "onStatusChanged: " + provider);
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                        Log.d(TAG, "onProviderEnabled: " + provider);
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        Log.d(TAG, "onProviderDisabled: " + provider);
                    }
                })
                .build();
        com.yayandroid.locationmanager.LocationManager.enableLog(true);
    }
}